package com.farmer.news.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.farmer.common.entity.AgriNews;
import com.farmer.common.result.Result;
import com.farmer.news.mapper.NewsMapper;
import com.farmer.news.service.NewsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 农业资讯服务实现类
 */
@Slf4j
@Service
public class NewsServiceImpl implements NewsService {

    @Autowired
    private NewsMapper newsMapper;

    @Override
    public Result<?> getNewsList(Integer pageNum, Integer pageSize, String category, Integer status, String keyword) {
        try {
            Page<AgriNews> page = new Page<>(pageNum, pageSize);
            QueryWrapper<AgriNews> queryWrapper = new QueryWrapper<>();

            if (StringUtils.hasText(category)) {
                queryWrapper.eq("category", category);
            }
            if (status != null) {
                queryWrapper.eq("status", status);
            }
            if (StringUtils.hasText(keyword)) {
                queryWrapper.and(wrapper -> wrapper
                        .like("title", keyword)
                        .or()
                        .like("content", keyword)
                );
            }

            queryWrapper.orderByDesc("is_top", "priority", "publish_time");
            Page<AgriNews> newsPage = newsMapper.selectPage(page, queryWrapper);

            Map<String, Object> result = new HashMap<>();
            result.put("records", newsPage.getRecords());
            result.put("total", newsPage.getTotal());
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);

            return Result.success("获取农业资讯列表成功", result);
        } catch (Exception e) {
            log.error("获取农业资讯列表失败：{}", e.getMessage(), e);
            return Result.error("获取农业资讯列表失败");
        }
    }

    @Override
    public Result<?> getNewsById(Long newsId) {
        try {
            AgriNews news = newsMapper.selectById(newsId);
            if (news == null) {
                return Result.error("资讯不存在");
            }

            // 增加浏览次数
            news.setViewCount(news.getViewCount() + 1);
            newsMapper.updateById(news);

            return Result.success("获取资讯详情成功", news);
        } catch (Exception e) {
            log.error("获取资讯详情失败：{}", e.getMessage(), e);
            return Result.error("获取资讯详情失败");
        }
    }

    @Override
    public Result<?> addNews(AgriNews news) {
        try {
            if (!StringUtils.hasText(news.getTitle())) {
                return Result.error("资讯标题不能为空");
            }

            // 设置默认值
            if (news.getViewCount() == null) {
                news.setViewCount(0);
            }
            if (news.getLikeCount() == null) {
                news.setLikeCount(0);
            }
            if (news.getShareCount() == null) {
                news.setShareCount(0);
            }
            if (news.getCommentCount() == null) {
                news.setCommentCount(0);
            }
            if (news.getStatus() == null) {
                news.setStatus(0); // 草稿状态
            }
            if (news.getIsFeatured() == null) {
                news.setIsFeatured(0);
            }
            if (news.getIsTop() == null) {
                news.setIsTop(0);
            }
            if (news.getPriority() == null) {
                news.setPriority(1);
            }

            int result = newsMapper.insert(news);
            if (result > 0) {
                return Result.success("添加农业资讯成功", news);
            } else {
                return Result.error("添加农业资讯失败");
            }
        } catch (Exception e) {
            log.error("添加农业资讯失败：{}", e.getMessage(), e);
            return Result.error("添加农业资讯失败");
        }
    }

    @Override
    public Result<?> updateNews(AgriNews news) {
        try {
            if (news.getId() == null) {
                return Result.error("资讯ID不能为空");
            }

            AgriNews existingNews = newsMapper.selectById(news.getId());
            if (existingNews == null) {
                return Result.error("资讯不存在");
            }

            int result = newsMapper.updateById(news);
            if (result > 0) {
                return Result.success("更新资讯信息成功");
            } else {
                return Result.error("更新资讯信息失败");
            }
        } catch (Exception e) {
            log.error("更新资讯信息失败：{}", e.getMessage(), e);
            return Result.error("更新资讯信息失败");
        }
    }

    @Override
    public Result<?> deleteNews(Long newsId) {
        try {
            if (newsId == null) {
                return Result.error("资讯ID不能为空");
            }

            int result = newsMapper.deleteById(newsId);
            if (result > 0) {
                return Result.success("删除资讯成功");
            } else {
                return Result.error("删除资讯失败");
            }
        } catch (Exception e) {
            log.error("删除资讯失败：{}", e.getMessage(), e);
            return Result.error("删除资讯失败");
        }
    }

    @Override
    public Result<?> getRecommendedNews(Integer limit) {
        try {
            if (limit == null || limit <= 0) {
                limit = 10;
            }

            QueryWrapper<AgriNews> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", 1)
                    .eq("is_featured", 1)
                    .orderByDesc("priority", "view_count")
                    .last("LIMIT " + limit);

            List<AgriNews> newsList = newsMapper.selectList(queryWrapper);
            return Result.success("获取推荐资讯成功", newsList);
        } catch (Exception e) {
            log.error("获取推荐资讯失败：{}", e.getMessage(), e);
            return Result.error("获取推荐资讯失败");
        }
    }

    @Override
    public Result<?> getNewsStatistics() {
        try {
            QueryWrapper<AgriNews> queryWrapper = new QueryWrapper<>();
            Long totalNews = newsMapper.selectCount(queryWrapper);

            queryWrapper.clear();
            queryWrapper.eq("status", 1);
            Long publishedNews = newsMapper.selectCount(queryWrapper);

            queryWrapper.clear();
            queryWrapper.eq("is_featured", 1);
            Long featuredNews = newsMapper.selectCount(queryWrapper);

            Map<String, Object> statistics = new HashMap<>();
            statistics.put("totalNews", totalNews);
            statistics.put("publishedNews", publishedNews);
            statistics.put("featuredNews", featuredNews);

            return Result.success("获取资讯统计信息成功", statistics);
        } catch (Exception e) {
            log.error("获取资讯统计信息失败：{}", e.getMessage(), e);
            return Result.error("获取资讯统计信息失败");
        }
    }
} 